package com.hanxiaozhang.tx.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.util.List;
import java.util.Map;

import com.hanxiaozhang.tx.dao.RepoDao;
import com.hanxiaozhang.tx.entity.RepoEntity;
import com.hanxiaozhang.tx.service.RepoService;
import org.springframework.transaction.annotation.Transactional;


/**
 * RocketMQ事务库存表
 *
 * @author hanxiaozhang
 * @email hanxiaozhang2018@sina.com
 * @date 2022-10-09
 */
@Slf4j
@Service
public class RepoServiceImpl implements RepoService {

    public static final int RETRY_REDUCE_NUM = 3;

    @Resource
    private RepoDao repoDao;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int reduce(Integer buyNum, Integer goodId) {
        for (int i = 1; i <= RETRY_REDUCE_NUM; i++) {
            log.info("货物id:[{}],尝试第{}次扣减,扣减数据量[{}]", goodId, i, buyNum);
            RepoEntity repo = repoDao.get(goodId);
            if (repo == null) {
                return 0;
            }
            // 避免数据库库存扣减小于零
            if (repo.getNum() - buyNum < 0) {
                return -1;
            }
            int affect = repoDao.updateGoodNum(repo.getNum() - buyNum, repo.getNum(), goodId);
            if (affect > 0) {
                return affect;
            }
        }
        return 0;
    }


}
